/*
  Copyright (c) 2013 LEROY Anthony <leroy.anthony@gmail.com>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program. If not, see http://www.gnu.org/licenses/gpl.txt
*/

package fr.sigma.labo.autostoptan;

import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created by aleroy on 19/06/13.
 */
public class SendDataTask extends AsyncTask<JSONObject, Void, HttpResponse> {

    @Override
    protected HttpResponse doInBackground(JSONObject... jsonObjects) {
        HttpResponse response = null;

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpPost httppost = new HttpPost("http://autostop.eu01.aws.af.cm/AutoStop/put");
        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Content-type", "application/json");

        try {
            // Add your data
            httppost.setEntity(new ByteArrayEntity(jsonObjects[0].toString().getBytes("UTF8")));
            // Execute HTTP Post Request
            System.out.println("Execute HTTP Post Request...");
            response = httpclient.execute(httppost);
            System.out.println("reponse: "+response.getEntity().toString());
        } catch (ClientProtocolException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }  catch (ConnectTimeoutException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return response;
    }

}
